<?php

namespace App\Library\Models;

use App\Library\Logic\ShopImageLogic;
use App\Library\Logic\ShopUserLogic;
use App\Library\Traits\AttributeTrait;
use App\Models\ShopProductModel;
use Encore\Admin\Grid;

class AdminShopProductModel extends ShopProductModel
{
    use AttributeTrait;

    /**
     * mainImgStr
     * @param AdminShopProductModel|null $self
     * @return string
     */
    public static function mainImgStr(?self $self): string
    {
        if (is_null($self)) return '';
        else if (!is_null($self->main_img_ids)) return '';
        $where = ['imgType' => 1, 'imgSourceType' => 4, 'imgSourceId' => $self->product_id];
        $array = ShopImageLogic::query()->where(humpToLine($where))->orderByDesc('img_is_cover')->orderBy('img_sort')
            ->pluck('img_url')->toArray();
        return empty($array) ? '' : implode(',', $array);
    }

    /**
     * descImgStr
     * @param AdminShopProductModel|null $self
     * @return string
     */
    public static function descImgStr(?self $self): string
    {
        if (is_null($self)) return '';
        else if (!is_null($self->desc_img_ids)) return '';
        $where = ['imgType' => 1, 'imgSourceType' => 5, 'imgSourceId' => $self->product_id];
        $array = ShopImageLogic::query()->where(humpToLine($where))->orderByDesc('img_is_cover')->orderBy('img_sort')
            ->pluck('img_url')->toArray();
        return empty($array) ? '' : implode(',', $array);
    }

    /**
     * videoStr
     * @param AdminShopProductModel|null $self
     * @return string
     */
    public static function videoStr(?self $self): string
    {
        if (is_null($self)) return '';
        else if (!is_null($self->video_id)) return '';
        $where = ['imgType' => 2, 'imgSourceType' => 4, 'imgSourceId' => $self->product_id];
        $imgUrl = ShopImageLogic::query()->where(humpToLine($where))->value('img_url');
        return $imgUrl ?? '';
    }

    public static function hUserId(Grid $grid, int $userId): void
    {
        if ($userId === config('app.superId')) return;
        $self = ShopUserLogic::findByWhere('userId', $userId, ['userMainId', 'userPeerPower']);
        if (is_null($self)) $grid->model()->where('user_id', 0);
        else if ($self->user_main_id === 0) $grid->model()->where('user_id', $userId);
        else {
            if ($self->user_peer_power === 0) $grid->model()->whereIn('add_user_id', $userId);
            else $grid->model()->whereIn('user_id', [$self->user_main_id, $userId]);
        }
    }
}
